<template>
  <el-dialog
    title="创建权限组"
    :visible="showDialog"
    @close="handleClose"
    @open="handelOpened"
  >
    <!-- 表单 -->
    <el-form
      ref="addRef"
      label-width="120px"
      :model="perDate"
      :rules="addFormRules"
    >
      <el-form-item label="用户名" prop="title">
        <el-input
          v-model="perDate.title"
          style="width: 80%"
          placeholder="请输入用户名"
        />
      </el-form-item>
      <el-form-item label="权限分配">
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          :props="{ label: 'title' }"
          :data="treeData"
          default-expand-all
          node-key="id"
          show-checkbox
        />
      </el-form-item>
    </el-form>
    <!-- footer插槽 -->
    <template v-slot:footer>
      <el-button @click.stop="handleClose">取消</el-button>
      <el-button type="primary" @click="getCheckedKeys">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { addPermisionAPI } from '@/api/permissions'
export default {
  name: 'AddPermision',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 权限数据
      treeData: [],
      // 新增权限信息表单
      perDate: {
        title: '',
        permissions: ''
      },
      // 表单校验规则
      addFormRules: {
        title: [
          {
            required: true,
            message: '请输入用户名，此信息必须填写',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.handelOpened()
  },
  methods: {
    // 添加用户
    async getCheckedKeys() {
      console.log(this.$refs.tree.getCheckedKeys())
      this.perDate.permissions = this.$refs.tree.getCheckedKeys()
      this.perDate.permissions.shift()
      try {
        // 整体校验
        // 发起新增请求
        await addPermisionAPI(this.perDate)
        // 关闭弹框
        this.handleClose()
        // 获取员工列表
        //   this.$parent.getEmpioyeeList()
        //  推荐子传父
        this.$emit('add-success')
        //   成功提示
        this.$message.success('添加成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 弹窗打开时
    async handelOpened() {
      // 获取权限组列表
      await this.$store.dispatch('permission/getPermissionTree')
      this.treeData = this.$store.state.permission.perDate
      console.log(this.treeData)
    },
    // 关闭弹窗
    async handleClose() {
      this.$refs.addRef.validate(async (valid) => {
        if (!valid) return
        // await this.$confirm(
        //   '此操作会清空已编辑数据，确定退出编辑吗？',
        //   '温馨提示',
        //   {
        //     type: 'warning'
        //   }
        // )
        this.$emit('update:showDialog', false)
        await this.$refs.addRef.resetFields()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
